# -*- coding: utf-8 -*-

"""
Module implementing MainWindow.
"""
import sys, pymysql
import baostock as bs
import pandas as pd
import datetime

from PyQt5.QtGui import QStandardItem, QBrush, QColor

from dbManagement import DataManagement
from PyQt5.QtCore import pyqtSlot, Qt
from PyQt5.QtWidgets import QMainWindow, QApplication, QTableWidgetItem

from Ui_mian import Ui_MainWindow


class MainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """

    def __init__(self, parent=None):
        self.ri_qi_arry = []
        self.ri_qi_arry2 = []
        self.stock_list = []
        self.conn = DataManagement()
        # 连接数据库
        self.cursor = self.conn.connect_sql()
        # 获取stocklist总行数
        self.stocklist_zong_hang_shu = self.conn.stocklist_zong_hang_shu()

        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.jian_li_shu_zu()
        self.zheng_li_list()
        self.xie_ru_shu_ju()
        self.xia_biao_shu_ju()
        self.hang_qing_shu_ju()

        # 连接信号槽#########单击
        self.tableWidget.cellClicked['int', 'int'].connect(MainWindow.on_tabWidget_tabBarClicked)

    # 整理20天日期并写入数组
    def jian_li_shu_zu(self):
        aa = 0;
        self.bb = 1;
        # 登录baostock服务器
        self.lg = bs.login()
        while self.bb <= 20:
            # 判断是否交易日
            self.ri_qi = (datetime.datetime.now() - datetime.timedelta(days=aa)).strftime("%Y-%m-%d")
            self.ri_qi2 = (datetime.datetime.now() - datetime.timedelta(days=aa)).strftime("%m-%d")
            self.guo_du_1 = bs.query_trade_dates(self.ri_qi)
            self.bb_1 = self.guo_du_1.get_row_data()[1]
            # 判断交易日，并放入指定数组self.ri_qi_arry
            if self.bb_1 == "1":
                #  建立数组
                self.ri_qi_arry.append(self.ri_qi)
                self.ri_qi_arry2.append(self.ri_qi2)
                self.bb += 1;
                aa += 1
                continue
            elif self.bb_1 == "0":
                aa += 1
                continue
            else:
                break

    # 整理数据库股票列表去重
    def zheng_li_list(self):
        aa = []
        cc = self.conn.stocklist_zong_hang_shu()
        for i in range(cc):
            rowCount = self.cursor.fetchone()
            # print(rowCount)
            # self.newstocklist rowCount[1]
            rowCount = rowCount[1]
            aa.append(rowCount)
            self.stock_list = list(set(aa))
            self.stock_list.sort(key=aa.index)

    # 写入数据建立板块表格
    def xie_ru_shu_ju(self):
        for f in range(len(self.ri_qi_arry)):
            item = QTableWidgetItem(self.ri_qi_arry2[f])
            # 修改行标头
            self.tableWidget.setHorizontalHeaderItem(f, item)

            # 如果是交易日，那么就要循环，写入前五大板块信息
            cc = self.conn.zhi_ding_jiao_yi_ri_shu_ju(self.ri_qi_arry[f])
            for it in range(cc):
                it1 = self.cursor.fetchone()
                if it >= 5:
                    break
                else:
                    # 获取指定数列段
                    it2 = it1[2]
                    it3 = it1[4]
                    it4 = it3 + "(" + ('%s') % it2 + ")"
                    # 写入每日前五大板块及板块涨停个数
                    it5 = QTableWidgetItem(it4)
                    self.tableWidget.setItem(it, f, it5)

        # country_item1 = QTableWidgetItem('还是我')
        # country_item2 = QTableWidgetItem('我')
        # country_item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        # 现在创建一个关于国家的表格对象。这个国家的单元格对象里面放入国旗和国家名称，单元格的对齐方式是：水平、垂直居中。
        # 下同
        # 修改列表头
        # self.tableWidget.setVerticalHeaderItem(0,country_item1)
        # 修改行标头
        # self.tableWidget.setHorizontalHeaderItem(0, country_item2)
        # 修改单元格内容
        # self.tableWidget.setItem(0, 0, country_item)

    # 写入数据建立下表表格
    def xia_biao_shu_ju(self):

        for f in range(len(self.stock_list)):
            item = QTableWidgetItem(self.stock_list[f])
            # 修改行标头
            self.tableWidget_2.setVerticalHeaderItem(f, item)

    def hang_qing_shu_ju(self):
        #### 登陆系统 ####
        lg = bs.login()
        for f in range(len(self.stock_list)):
            aaa = 'sz.%s' % self.stock_list[f]
            bbb = 'sh.%s' % self.stock_list[f]
            # 数组内的格式是倒的
            if self.stock_list[f][0:2] != "60":
                rs = bs.query_history_k_data_plus(aaa,
                                                  "pctChg",
                                                  start_date=self.ri_qi_arry[19], end_date=self.ri_qi_arry[0],
                                                  frequency="d", adjustflag="3")

            else:
                rs = bs.query_history_k_data_plus(bbb,
                                                  "pctChg",
                                                  start_date=self.ri_qi_arry[19], end_date=self.ri_qi_arry[0],
                                                  frequency="d", adjustflag="3")
            data_list = []
            bo_dong = []
            while (rs.error_code == '0') & rs.next():
                # 获取一条记录，将记录合并在一起

                data_list.append(rs.get_row_data())

                self.result = pd.DataFrame(data_list, columns=rs.fields)

            # print(data_list)

            # 把数组颠倒过来
            list_2 = [data_list[0]]
            for i in range(1, len(data_list)):
                list_2.insert(0, data_list[i])
            # 开始放入单元格

            for d in range(len(list_2)):

                dddd = "%.2f" % float(list_2[d][0])
                # print(dddd)
                if dddd >= "9.8":
                    shu_ju = QTableWidgetItem(dddd)
                    self.tableWidget_2.setItem(f, d, shu_ju)
                    self.tableWidget_2.item(f, d).setForeground(QBrush(QColor(255, 0, 0)))
                    # print("ok")
                else:
                    shu_ju = QTableWidgetItem(dddd)
                    self.tableWidget_2.setItem(f, d, shu_ju)
                    # print("no")
                # print(c,d)

                # self.tableWidget.setItem(it, f, it5)

                # 修改单元格内容
                # self.tableWidget.setItem(c, data_list, self.result)

        #### 登出系统 ####
        bs.logout()

    # 单击槽函数
    @pyqtSlot(int, int)
    def on_tabWidget_tabBarClicked(row, column):
        """
        Slot documentation goes here.

        @param index DESCRIPTION
        @type int
        """
        print(row, column)


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    mb = MainWindow()
    mb.show()
    sys.exit(app.exec_())
